const schedule = require('node-schedule');
const push = require('../alicloud/push');
const messageDao = require('../dao/messageDao');
const messageCfgDao = require('../dao/messageCfgDao');
const request = require('../util/request');

let jobMaps = {};

/**
 * 
_id
title: { type: String },
contentTemplate: { type: String }, 
messageType:{type:String,enum:messageTypes.map(v=>v.value)},
sendTime:{type:Date},
receiverList:{type:String},
sendSms:{type:Boolean,default:false},
sendNotice: { type: Boolean, default:false},
 */
function sendMessage(data){

    let receiver,receiverList = [],messages = [];
    if(data.receiverList){
        receiver = data.receiverList;
        receiverList = receiver.split(',');
    }else{
        receiver = 'ALL';
    }

    if(receiver == 'ALL'){

        messages.push({
            userId:"ALL",
            title:data.title,
            body:data.contentTemplate,
            createTime:new Date,
            read:false
        })
        
    }else{
        messages = receiverList.map(v=>{
            return {
                userId:v,
                title:data.title,
                body:data.contentTemplate,
                createTime:new Date,
                read:false
            }
        })
    }

    messageDao.saveBatch(messages,(err,results)=>{
        if(!err){
            results = results || [];
            console.log('send',results.length,'message');
        }else{
            console.error(err);
        }
    })
}

function sendNotice(data){
    let receiver,receiverList = [],messages = [];
    if(!data.receiverList){
        data.receiverList = 'ALL'
    }

    push.getPush()
    .push({
        AppKey:push.getAppKey(),
        //推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
        Target:"ACCOUNT", 
        //根据Target来设定，如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
        TargetValue:data.receiverList,
        PushType:"NOTICE", //消息类型 MESSAGE NOTICE
        //设备类型 ANDROID iOS ALL.
        DeviceType:"ALL",
        Title:data.title,
        Body:data.contentTemplate,
    },(err,result)=>{
        if(!err){
            
            console.log(result);
        }else{
            console.error(err);
        }
    })
}

function jobFunc(data){
    
    sendMessage(data);
    if(data.sendNotification){
        sendNotice(data)
    }
    
}

const apis = {
    addJob:function(data){
        let job = null;
        if(jobMaps[data._id]){
            jobMaps[data._id].cancel();
        }
        if(data.sendTime){
            job = schedule.scheduledJobs(new Date(data.sendTime),function(){
                jobFunc(data);
                job.cancel();
                delete jobMaps[data._id]
            })
            jobMaps[data._id] = job;
        }
    },
    initJob:function(){

        messageDao.query([
            {
                "$match":{
                    messageType:'oriented',
                    enable:true
                }
            }
        ],(err,docs)=>{

            if(err){
                console.error(err);
                return;
            }

            docs = docs || [];

            docs.forEach(v=>{
                apis.addJob(v);
            })
        })

    }
}

module.exports = apis;